//
//  SSEmoticonInputView.swift
//  表情键盘
//
//  Created by 叶竞泽 on 2017/2/9.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit

/// 表情输入视图
class SSEmoticonInputView: UIView {
    
    // MARK: - 属性
    
    fileprivate let cellIdentifier = "cellIdentifier"
    
    /// 表情集合视图
    @IBOutlet weak var collectionView: UICollectionView!
    
    /// 工具栏
    @IBOutlet weak var toolbar: SSEmoticonToolbar!
    
    /// 分页控制器
    @IBOutlet weak var pageControl: UIPageControl!
    
    /// 选中表情回调闭包属性
    fileprivate var selectedEmoticonCallback: ((_ emoticon: SSEmoticon?) -> ())?
    
    /// 类方法
    ///
    /// - Returns: 返回表情视图
    class func inputView(selectedEmoticon: @escaping (_ emoticon: SSEmoticon?) -> ()) -> SSEmoticonInputView? {
        
        guard let inputView = UINib(nibName: "SSEmoticonInputView", bundle: nil).instantiate(withOwner: nil, options: nil).first as? SSEmoticonInputView else {
            return nil
        }
        
        inputView.selectedEmoticonCallback = selectedEmoticon
        
        return inputView
    }
    
    // MARK: - 生命周期
    
    override func awakeFromNib() {
        
        collectionView.backgroundColor = UIColor.white
        
        // 1.注册可重用cell
        collectionView.register(SSEmoticonCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
        // 2.设置工具栏代理
        toolbar.delegate = self
        
        // 6.设置分页控件的图片
        let bundle = SSEmoticonManager.shared.bundle
        guard let image = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil), let selectedimage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else {
            return
        }
        
        // 使用填充图片设置颜色
        //        pageControl.pageIndicatorTintColor = UIColor(patternImage: image ?? UIImage())
        //        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: selectedimage ?? UIImage())
        pageControl.setValue(selectedimage, forKey: "_currentPageImage")
        pageControl.setValue(image, forKey: "_pageImage")
    }
}

// MARK: - 数据源方法
extension SSEmoticonInputView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 页面的数量 = SSEmoticonManager.shared.packages[section].emoticons.count / 20
        return SSEmoticonManager.shared.packages[section].numberOfPages
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? SSEmoticonCell {
            
            // 设置cell页面的表情数组
            cell.emoticons = SSEmoticonManager.shared.packages[indexPath.section].emoticons(page: indexPath.item)
            cell.delegate = self
            return cell
        }
        return UICollectionViewCell()
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return SSEmoticonManager.shared.packages.count
    }
    
}

// MARK: - 数据源代理
extension SSEmoticonInputView: UICollectionViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 1.获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        
        // 2.获取当前显示的cell的indexpath
        let paths = collectionView.indexPathsForVisibleItems
        
        // 3.判断中心点在哪一个indexpath上
        var targetIndexPath: IndexPath?
        
        for indexpath in paths {
            
            // 根据indexpath获得cell
            let cell = collectionView.cellForItem(at: indexpath)
            // 判断中心点位置
            if cell?.frame.contains(center) == true {
                targetIndexPath = indexpath
                break
            }
        }
        
        // 4.判断是否找到目标的indexpath
        // indexpath.section对应的就是toolbar的分组
        
        guard let target = targetIndexPath else { return }
        
        toolbar.selectedIndex = target.section
        
        // 5.设置分页控件
        pageControl.currentPage = target.section
        
    }
    
}

// MARK: - 实现代理方法
extension SSEmoticonInputView: SSEmoticonCellDelegate {
    
    /// 选中的表情回调
    ///
    /// - Parameters:
    ///   - cell: 分页cell
    ///   - emoticon: 选中的表情
    func emoticonCellDidSelectedEmoticon(cell: SSEmoticonCell, emoticon: SSEmoticon?) {
        
        // 执行闭包
        selectedEmoticonCallback?(emoticon)
        guard let em = emoticon else { return }
        // 如果当前的collectionView就是最近分组,就不添加最近的表情
        let indexPath = collectionView.indexPathsForVisibleItems.first
        if indexPath?.section == 0 {
            return
        }
        // 添加最近使用的表情
        SSEmoticonManager.shared.recentEmoticon(emoticon: em)
        // 刷新数据
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    }
}

// MARK: - 实现代理方法
extension SSEmoticonInputView: SSEmoticonToolbarDelegate {
    
    func emoticonToolbarDidSelectedItemIndex(toolBar: SSEmoticonToolbar, index: Int) {
        
        // 滚动collectionView - 滚动到每个分组的第0页
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
}
